package com.heer.gymnasium.module.map.views;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.constants.IConstants;
import com.heer.gymnasium.module.map.CheckPermissionsActivity;
import com.heer.gymnasium.module.map.adapter.LocationAdapter;
import com.zhihuiyun.library.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yan
 * on 2018/3/8
 */

public class LocationSetActivity extends CheckPermissionsActivity implements PoiSearch.OnPoiSearchListener, AMapLocationListener {
    private static final int RES_ID_LAYOUT = R.layout.layout_location_set;
    private static final int RES_ID_ADDRESS = R.id.layout_locaion_set_address_tv;
    private static final int RES_ID_SEARCH_ET = R.id.layout_locaion_set_search_et;
    private static final int RES_ID_SEARCH_TV = R.id.layout_locaion_set_search_tv;
    private static final int RES_ID_LOCATION_TV = R.id.layout_locaion_set_location_tv;
    private static final int RES_ID_LOCATION_LV = R.id.layout_locaion_set_location_lv;

    @BindView(RES_ID_LOCATION_LV)
    ListView listView;
    @BindView(RES_ID_SEARCH_ET)
    EditText editText;
    @BindView(RES_ID_ADDRESS)
    TextView textView;
    private LocationAdapter adapter;

    private List<PoiItem> data;
    private Activity $this;
    public static final int REQUSTCODE = 2;
    public static final int RESULTCODE_LOCATION = 3;
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索


    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(RES_ID_LAYOUT);

    }

    @Override
    protected void initView() {
        super.initView();
        data = new ArrayList<>();
        adapter = new LocationAdapter(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                LatLonPoint latLonPoint = data.get(i).getLatLonPoint();
                SPUtils.put($this, SPUtils.SP_LA, latLonPoint.getLatitude() + "");
                SPUtils.put($this, SPUtils.SP_LO, latLonPoint.getLongitude() + "");
                SPUtils.put($this, SPUtils.SP_ADCODE, data.get(i).getAdCode());
                SPUtils.put($this, SPUtils.SP_ADNAME, data.get(i).getAdName());
                Intent intent = new Intent();
                intent.putExtra(EXTRA_DATA, data.get(i).getAdName());
                $this.setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    @OnClick(RES_ID_SEARCH_TV)
    public void onClickForSearch() {
        query = new PoiSearch.Query(editText.getText().toString(), "", "022");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setCityLimit(true);
        query.setPageSize(15);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);// 设置查第一页
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }


    @OnClick(RES_ID_LOCATION_TV)
    public void onClickForLocation() {
        location();
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (poiResult != null && poiResult.getQuery() != null) {// 搜索poi的结果
                if (poiResult.getQuery().equals(query)) {// 是否是同一条
                    poiResult = poiResult;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

                    if (poiItems != null && poiItems.size() > 0) {
                        data.clear();
                        data.addAll(poiItems);
                        adapter.setData(data);
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        showSuggestCity(suggestionCities);
                    } else {
                        ToastUtil.show($this,
                                "没有搜索结果");
                        data.clear();
                        adapter.setData(data);
                    }
                }
            } else {
                data.clear();
                adapter.setData(data);
                ToastUtil.show($this,
                        "没有搜索结果");
            }
        } else {
            ToastUtil.showerror(this, rCode);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * poi没有搜索到数据，返回一些推荐城市的信息
     */
    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "推荐城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名称:" + cities.get(i).getCityName() + "城市区号:"
                    + cities.get(i).getCityCode() + "城市编码:"
                    + cities.get(i).getAdCode() + "\n";
        }
        ToastUtil.show(this, infomation);

    }

    /**
     * 启动定位
     */
    private void location() {
        mLocationOption = new AMapLocationClientOption();
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setNeedAddress(true);
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        IConstants.ADCODE = aMapLocation.getAdCode();
        IConstants.LA = aMapLocation.getLatitude() + "";
        IConstants.LO = aMapLocation.getLongitude() + "";
        SPUtils.put($this, SPUtils.SP_LA, aMapLocation.getLatitude() + "");
        SPUtils.put($this, SPUtils.SP_LO, aMapLocation.getLongitude() + "");
        SPUtils.put($this, SPUtils.SP_ADCODE, aMapLocation.getAdCode());
        SPUtils.put($this, SPUtils.SP_ADNAME, aMapLocation.getDistrict());
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DATA, aMapLocation.getDistrict());
        this.setResult(RESULTCODE_LOCATION, intent);
        finish();
    }
}
